const express = require('express');
const axios = require('axios');
const router = express.Router();

// const app = express();
// const PORT = 3004;

router.get('/', async (req, res) => {

    try {
        let { trainDate, fromStation, toStation, purposeCodes } = req.query;
        // trainDate = '2023-06-05'
        // fromStation = 'SHH'
        // toStation = 'TJP'

        const { data } = await axios.get('https://kyfw.12306.cn/otn/leftTicket/query', {
            params: {
                "leftTicketDTO.train_date": trainDate,
                "leftTicketDTO.from_station": fromStation,
                "leftTicketDTO.to_station": toStation,
                purpose_codes: purposeCodes,
            },
            headers: {
                // 请求查询接口成功关键语句
                /**
                 * 设置cookie为以下配置中的任何一个即可请求成功，12306官网为全部配置：
                 * _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5929%u6D25%2CTJP; _jc_save_fromDate=2023-06-03; _jc_save_toDate=2023-06-03; _jc_save_wfdc_flag=dc; JSESSIONID=
                 */
                Cookie: 'JSESSIONID='
                // Cookie: `_jc_save_fromDate=${trainDate};_jc_save_fromStation=${fromStation}; _jc_save_toStation=${toStation}; _jc_save_toDate=${trainDate}`
            }
        });

        console.warn('sss',data)

        // 过滤数据
        const { data: { result, map }, httpstatus, status } = data
        let list = []

        if (httpstatus === 200 || status === true) {
            result.forEach((item) => {
                const currentItem = item.split('|')

                const config = {
                    train_no: currentItem[2],
                    train_date: trainDate,
                    '车次': currentItem[3],
                    '出发时间': currentItem[8],
                    '出发车站': map[currentItem[6]],
                    '到达时间': currentItem[9],
                    '到达车站': map[currentItem[7]],
                    '出发车站类型': currentItem[4] === currentItem[6] ? '始' : '过',
                    '到达车站类型': currentItem[5] === currentItem[7] ? '终' : '过',
                    '历时': currentItem[10],
                    '动卧': '',
                    '硬卧': '',
                    '硬座': '',
                    '软座': '',
                    '软卧': '',
                    '高级软卧': '',
                    '二等座': '',
                    '无座': '',
                    '一等座': '',
                    '商务座': '',
                }

                const train = config['车次'].substr(0, 1)

                if (train === 'D' || train === 'G' || train === 'C') {
                    config['一等座'] = currentItem[31] || ''
                    config['二等座'] = currentItem[30] || ''
                    config['无座'] = currentItem[26] || ''
                }

                if (train === 'G' || train === 'C') {
                    config['商务座'] = train === 'G' ? currentItem[32] : currentItem[25]
                }

                if (train === 'Y') {
                    config['软座'] = currentItem[24] || ''
                    config['硬座'] = currentItem[29] || ''
                    config['无座'] = currentItem[26] || ''
                }

                if (train === 'K' ||
                    train === 'T' ||
                    train === 'Z') {
                    config['软卧'] = currentItem[23] || ''
                    config['高级软卧'] = currentItem[21] || ''
                    config['硬卧'] = currentItem[28] || ''
                    config['硬座'] = currentItem[29] || ''
                    config['无座'] = currentItem[26] || ''
                }

                if (train === 'D') {
                    config['动卧'] = currentItem[33] || ''
                }


                list.push(config)
            })
        }


        // 设置强缓存，6秒内不重新验证
        res.setHeader('Cache-Control', 'public, max-age=6'); // 单位是秒，这里是6秒
        res.setHeader('Expires', new Date(Date.now() + 6000).toUTCString()); // 过期时间设置为6秒后
        // 返回查询结果
        res.json(list);

    } catch (error) {
        res.status(500).json([]);
    }
});


// app.listen(PORT, () => {
//     console.log(`Server is running on port ${PORT}`);
// });

module.exports = router
